
import { useState, forwardRef, memo, useRef, useMemo, useEffect, lazy, Suspense } from 'react'
import { Button, Form, Row, Col, Input, Select, InputNumber, message } from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'
import AddFile from '../AddFile'
import LdCloner from '../../../../components/LdCloner'
import { secretOptions } from "../../../../utils/constant";
import bus from '../../../../utils/eventBus';
import './index.scss'
const MakeLoading = lazy(() => import('../MakeLoading'))
const BurnView = forwardRef((props: any, ref: any) => {
    const navigate = useNavigate()
    const location = useLocation()
    const { onClose } = props
    console.log('刷新了')
    const formRef = useRef<any>(null)
    const addFile = useRef<any>(null)
    const ldCloner = useRef<any>(null)
    const diskTypeList = useRef<any[]>([
        {
            value: 1,
            label: "CD",
        },
        {
            value: 2,
            label: "DVD",
        },
    ])
    const [diskType, setDiskType] = useState<number>(1)
    const [showLoading, setShowLoading] = useState<boolean>(false)
    const [secretList, setSecretList] = useState<any[]>([...secretOptions])
    const [submitPercent, setSubmitPercent] = useState<number>(0)
    const diskTypeChange = () => {
        const { diskType } = formRef.current.getFieldsValue()
        setDiskType(diskType)
    }
    const getSelect = (value: string) => {
        formRef.current.setFieldsValue({
            burnerId: value
        })
    }
    const handleSubmit = () => {
        formRef.current.validateFields().then((res: any) => {
            const { diskType } = res
            const count = addFile.current?.fileCount();
            if (count === 0) {
                return message.warning("请上传要刻录的文件！");
            }
            const isSuccess = addFile.current?.checkIsUploadSuccess();
            if (!isSuccess.success) {
                return message.warning(isSuccess.message);
            }
            const payload = {
                ...res,
                ...ldCloner.current?.getBurnInfo(),
                taskInfo: {
                    ...res,
                    fileSizeLabel: addFile.current?.totalSize,
                    fileSize: addFile.current?.totalSizeUnit,
                    diskTypeLabel: diskTypeList.current.find((item: any) => item.value === diskType)?.label,
                },
                replyId: `${new Date().getTime()}`,
                window: "刻录光盘",
                paths: isSuccess.fileList.map((item: any) => item.path),
            };
            setShowLoading(true)
            window.chromePro.burnSubmitNt(JSON.stringify(payload));
        }).catch(() => {

        })
    }
    const burnSubmitNtFinished = (res: any) => {
        console.log("提交刻录完成", res);
        if (res.code === 200) {
            setShowLoading(false)
            onClose && onClose()
        } else {
            message.error(res.message)
            setShowLoading(false)
        }
    }
    const getUserAuthSecretFinished = (res: any) => {
        if (res.code === 200) {
            res.data.map((item: any) => {
                item.label = item.secretLabel
                item.value = item.secret
            })
            setSecretList(res.data)
            if (res.data.length > 0) {
                formRef.current.setFieldsValue({
                    secret: res.data[0].value
                })
            }
        }
    }
    const burnSubmitpProcessNtFinished = (res: any) => {
        console.log("镜像提交进度", res);
        if (res.code !== 200) {
            setShowLoading(false)
            return;
        }
        // 生成iso进度
        if (res.data.type === 1) {
            setSubmitPercent(res.data.progress)
            if (res.data.progress >= 100) {
                onClose && onClose()
                if (location.pathname === '/layout/burn') return
                navigate('/layout/burn')
            }
        }
    }
    useEffect(() => {
        formRef.current.setFieldsValue({
            diskType: 1
        })
        window.chromePro.getUserAuthSecret();
        bus.addListener('burnSubmitNtFinished', burnSubmitNtFinished)
        bus.addListener('getUserAuthSecretFinished', getUserAuthSecretFinished)
        bus.addListener('burnSubmitpProcessNtFinished', burnSubmitpProcessNtFinished)
    }, [])
    useEffect(() => {
        return () => {
            bus.removeListener('burnSubmitNtFinished', burnSubmitNtFinished)
            bus.removeListener('getUserAuthSecretFinished', getUserAuthSecretFinished)
            bus.removeListener('burnSubmitpProcessNtFinished', burnSubmitpProcessNtFinished)
        }
    }, [])
    return (
        <>
            <div className="tray-burn">
                <div className="box-bd">
                    <div className="content flex-start">
                        <div className="preview-container">
                            <AddFile diskType={diskType} ref={addFile}></AddFile>
                        </div>
                        <div className="setting-container">
                            <div className="setting-form">
                                <Form ref={formRef} style={{ width: '98%' }} labelCol={{ span: 4 }}>
                                    <h3>刻录设置</h3>
                                    <Row gutter={24} className="p-10 mt-10">
                                        <Col span={24}>
                                            <Form.Item label="刻录机" name="burnerId" rules={[{ required: true, message: '请选择刻录机' }]}>
                                                <LdCloner ref={ldCloner} getSelect={getSelect}></LdCloner>
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="标题" name="title" rules={[{ required: true, message: '请输入标题' }]}>
                                                <Input placeholder="请输入标题" maxLength={30} />
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="密级" name="secret" rules={[{ required: true, message: '请选择密级' }]}>
                                                <Select options={secretList} placeholder="请选择密级"></Select>
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="张数" name="paperSize" rules={[{ required: true, message: '请输入张数' }]}>
                                                <InputNumber style={{ width: '100%' }} placeholder='请输入张数' min={1} max={50} precision={0} controls={false} />
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="类型" name="diskType" rules={[{ required: true, message: '请选择类型' }]}>
                                                <Select options={diskTypeList.current} onChange={diskTypeChange} placeholder="请选择类型"></Select>
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="光盘密码" name="password">
                                                <Input placeholder="请输入密码" maxLength={12} />
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </Form>
                            </div>
                            <div className="footer">
                                <Button type="primary" className="submit-button" onClick={handleSubmit}>提交刻录</Button>
                            </div>
                        </div>
                    </div>
                </div>
                <Suspense>
                    {
                        showLoading ? <MakeLoading percent={submitPercent} /> : null
                    }
                </Suspense>
            </div>
        </>
    )
})
export default memo(BurnView)